package com.ken.zeratul.dlock.utils;

import cn.hutool.core.util.ObjectUtil;
import com.ken.zeratul.commons.spring.SpringUtils;
import com.ken.zeratul.dlock.annotation.DLockType;
import com.ken.zeratul.dlock.lock.base.BaseDLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 分布式锁工具类
 */
@Slf4j
public class DLockUtils {

    private static BaseDLock baseDLock;

    static {
        baseDLock = SpringUtils.getBean(BaseDLock.class);
        if (ObjectUtil.isNull(baseDLock)) {
            log.warn("【分布式锁】未找到合适的分布式锁实现类");
        }
    }

    /**
     * 阻塞锁
     */
    public static void lock(DLockType dLockType, String key){
        if (ObjectUtil.isNull(baseDLock)) return;
        baseDLock.lock(dLockType, key);
    }

    /**
     * 非阻塞锁
     * @param key
     * @param timeout
     * @return
     */
    public static boolean tryLock(DLockType dLockType, String key, Integer timeout){
        if (ObjectUtil.isNull(baseDLock)) return false;
        return baseDLock.tryLock(dLockType, key, timeout);
    }

    /**
     * 解锁
     */
    public static void unlock(){
        if (ObjectUtil.isNull(baseDLock)) return;
        baseDLock.unlock();
    }
}
